﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace _93Ini文件读取类IniFile
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            IniFile ini = new IniFile();
            ini.ReadFile(@"D:\Apeixun\ShiXun\MyHomeWork\weekend-homework\20201211\贺佳良\3\config.txt");
            string ip = ini.GetString("连接信息", "主机");
            Console.WriteLine(ip);
            string ip1 = ini.GetString("设置", "音量");
            Console.WriteLine(ip1);
        }
    }

    internal class IniFile
    {
        //定义一个字典，其中一个string为字典
        private Dictionary<string, Dictionary<string, string>> dic = new Dictionary<string, Dictionary<string, string>>();

        public void ReadFile(string path)
        {
            if (!File.Exists(path))
            {
                Console.WriteLine("文件不存在");
            }
            string[] array = File.ReadAllLines(path);
            string PrimaryKey = "";
            for (int i = 0; i < array.Length; i++)
            {
                //跳过空行
                if (array[i] == "")
                {
                    continue;
                }
                //去除首位末尾空格
                array[i].Trim();
                //查找主键
                if (array[i].StartsWith("["))
                {
                    PrimaryKey = array[i].Substring(1, array[i].Length - 2);
                    //添加
                    dic.Add(PrimaryKey, new Dictionary<string, string>());
                }
                //寻找“=”，拆分键值对
                else if (array[i].Contains("="))
                {
                    string[] KeyValue = array[i].Split('=');
                    dic[PrimaryKey].Add(KeyValue[0].TrimStart(), KeyValue[1].TrimEnd());
                }
            }
        }

        //返回值
        public string GetString(string PrimaryKey, string key)
        {
            return dic[PrimaryKey][key];
        }
    }
}